package com.cooper.mediadb.online;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.cooper.scraper.DownloadException;
import com.cooper.scraper.HttpDownload;

public abstract class AnalyzeVideo {

	private static final String WASU_SRC_REG = "<script\\s+type=\"text\\/javascript\">\\s*var\\s+_playUrl\\s*=\\s*'([^']+)'";

	public static AnalyzeVideo createAnalyzeVideo(
			MediaSource sources, String format) {
		switch (sources.getSrc()) {
		case MediaSrcMgr.SRC_PPTV:
			return new AnalyzePPTV(sources.getUrl(), format);
		case MediaSrcMgr.SRC_QIYI:
			return new AnalyzeQIYI(sources.getUrl(), format);
		case MediaSrcMgr.SRC_SOHU:
			return new AnalyzeSHOUHU(sources.getUrl(), format);
		case MediaSrcMgr.SRC_YUGAOPIAN:
			return new AnalyzeYUGAOPIAN(sources.getUrl(), format);
		case MediaSrcMgr.SRC_WASU:
			return new AnalyzeDirect(sources.getUrl(), format,
					WASU_SRC_REG, 1);
		case MediaSrcMgr.SRC_TUDOU:
			if (format.equals("super")) {
				format = "super2";
			}
			return new AnalyzeDefault(sources.getUrl(), format,
					true);
		default:
			return new AnalyzeDefault(sources.getUrl(), format,
					false);
		}
	}

	protected String format;
	protected String url = null;
	//protected HttpDownload httpDownload;

	public AnalyzeVideo(String format) {
		super();
		this.format = format;
	}

	public AnalyzeVideo(String url, String format) {
		super();
		this.format = format;
		this.url = url;
	}

	protected String getSelectFormatVideoId(Map<String, String> vedioIds) {
		if (vedioIds.size() == 1) {
			return vedioIds.values().toArray(new String[0])[0];
		}

		String formatVedioID = vedioIds.get(format);
		String testFormat = format;
		while (formatVedioID == null) {
			testFormat = MediaSrcMgr.getDownFormat(testFormat);
			if (testFormat == null) {
				break;
			} else {
				formatVedioID = vedioIds.get(testFormat);
			}
		}
		testFormat = format;
		while (formatVedioID == null) {
			testFormat = MediaSrcMgr.getUpFormat(testFormat);
			if (testFormat == null) {
				break;
			} else {
				formatVedioID = vedioIds.get(testFormat);
			}
		}

		if ((formatVedioID == null) && (vedioIds.size() > 0)) {
			formatVedioID = vedioIds.values().toArray(new String[0])[0];
		}
		return formatVedioID;
	}

	public abstract List<String> analyzeVideo() throws DownloadException,
			IOException;
}
